package net.chenlin.dp.modules.business.service.impl;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import net.chenlin.dp.common.exception.RRException;
import net.chenlin.dp.common.utils.ExcelImportAnalysisUtils;
import net.chenlin.dp.modules.business.dao.DeviceCalibrationMapper;
import net.chenlin.dp.modules.business.dao.DeviceRegisterMapper;
import net.chenlin.dp.modules.business.dao.GenTerminalSimCounterMapper;
import net.chenlin.dp.modules.business.dao.TerminalElectricEnergyDataMapper;
import net.chenlin.dp.modules.business.entity.TerminalSimEntity;
import net.chenlin.dp.modules.business.entity.po.DeviceCalibrationDataPo;
import net.chenlin.dp.modules.business.entity.po.ExceFilePo;
import net.chenlin.dp.modules.business.entity.po.ExcelmportDataPo;
import net.chenlin.dp.modules.business.entity.po.TerminalElectricEnergyDataPo;
import net.chenlin.dp.modules.business.listener.SysCaseServiceImportExcelListener;
import net.chenlin.dp.modules.business.service.DataImportService;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author Yangsm
 * @ClassName: DataImportServiceImpl
 * @Description: TODO
 * @date 2022年10月26日 11:12
 */
@Service
public class DataImportServiceImpl implements DataImportService {

    @Autowired
    private GenTerminalSimCounterMapper genTerminalSimCounterMapper;

    @Autowired
    private TerminalElectricEnergyDataMapper dataMapper;

    @Autowired
    private DeviceRegisterMapper deviceRegisterMapper;

    @Autowired
    private DeviceCalibrationMapper deviceCalibrationMapper;

    @Override
    public Boolean insertListData(List<TerminalSimEntity> list) {
        Boolean b = genTerminalSimCounterMapper.importData(list);
        return b;
    }

    @Override
    public void saveSubject(MultipartFile multipartFile, DataImportService dataImportService) {
        if (multipartFile.isEmpty()) {
            throw new RRException("文件异常,请重新选择");
        }
        String fileName = multipartFile.getOriginalFilename();
        //判断文件类型
        if (StringUtils.isNotBlank(fileName)) {
            if (!fileName.endsWith(ExcelTypeEnum.XLS.getValue()) && !fileName.endsWith(ExcelTypeEnum.XLSX.getValue())) {
                throw new RRException("文件格式错误,请重新选择 xlsx 或 xls 格式文件");
            }
            try {
                //有个很重要的点 UserExcelListener 不能被spring管理，要每次读取excel都要new,然后里面用到spring可以构造方法传进去
                EasyExcel.read(multipartFile.getInputStream(),
                        TerminalSimEntity.class,
                        new SysCaseServiceImportExcelListener(dataImportService)).sheet().doRead();
            } catch (Exception e) {
                e.printStackTrace();
                throw new RRException(e.getMessage());
            }
        }

    }

    @Override
    public void electricExcel(MultipartFile file) {
        if (Objects.isNull(file) || file.isEmpty()) {
            throw new RRException("导入文件为空");
        }
        String filename = file.getOriginalFilename();
        if (filename == null) {
            throw new RRException("文件名为空");
        }
        try {
            // 调用解析文件方法
            List<TerminalElectricEnergyDataPo> list = ExcelImportAnalysisUtils.parseRowCell(filename, file.getInputStream(), 4);
            dataMapper.batchInsert(list);
        } catch (IOException e) {
            throw new RRException(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @Override
    @Transactional
    public void deviceExcel(MultipartFile file) {

        if (Objects.isNull(file) || file.isEmpty()) {
            throw new RRException("导入文件为空");
        }
        String filename = file.getOriginalFilename();
        if (filename == null) {
            throw new RRException("文件名为空");
        }
        try {
            ExceFilePo filePo = new ExceFilePo();
            filePo.setFileName(filename);
            filePo.setImportTime(new Date());
            // 调用解析文件方法
            List<ExcelmportDataPo> list = ExcelImportAnalysisUtils.deviceExcelParseRowCell(filename, file.getInputStream(), 0);
            list.stream().forEach(excelmportDataPo -> {
                Date writeTime = excelmportDataPo.getWriteTime();
                System.out.println(writeTime);
                Calendar calendar = Calendar.getInstance();
                calendar.setTime(writeTime); // 设置当前时间
                calendar.add(Calendar.DATE, -1); // 前一天
                Date yesterday = calendar.getTime(); // 获取前一天的日期
                System.out.println("昨天的日期是: " + yesterday);
                excelmportDataPo.setAssertTime(yesterday);
            });
            deviceRegisterMapper.batchInsertByExcel(list);
            Date writeTime = list.get(0).getWriteTime();
            String format = new SimpleDateFormat("yyyy-MM-dd").format(writeTime);
            filePo.setImportMeteringTime(format);
            deviceRegisterMapper.insertExcelImportInfo(filePo);
        } catch (IOException e) {
            throw new RRException(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    @Transactional
    public ExceFilePo importExcelImportData(MultipartFile file) throws Exception {

        if (Objects.isNull(file) || file.isEmpty()) {
            throw new RRException("导入文件为空");
        }
        String filename = file.getOriginalFilename();
        if (filename == null) {
            throw new RRException("文件名为空");
        }
        ExceFilePo filePo = new ExceFilePo();
        filePo.setFileName(filename);
        filePo.setImportTime(new Date());
        // 调用解析文件方法
        List<ExcelmportDataPo> list = ExcelImportAnalysisUtils.deviceExcelParseRowCell(filename, file.getInputStream(), 0);
        if(CollectionUtils.isNotEmpty(list)){
            deviceRegisterMapper.batchInsertByExcel(list);
            Date writeTime = list.get(0).getWriteTime();
            String format = new SimpleDateFormat("yyyy-MM-dd").format(writeTime);
            filePo.setImportMeteringTime(format);
        }
        return filePo;
    }

    @Override
    @Transactional
    public void importDeviceCalibration(MultipartFile file) {

        if (Objects.isNull(file) || file.isEmpty()) {
            throw new RRException("导入文件为空");
        }
        String filename = file.getOriginalFilename();
        if (filename == null) {
            throw new RRException("文件名为空");
        }
        try {
            ExceFilePo filePo = new ExceFilePo();
            filePo.setFileName(filename);
            filePo.setImportTime(new Date());
            // 调用解析文件方法
            List<DeviceCalibrationDataPo> list = ExcelImportAnalysisUtils.deviceCalibrationExcelParseRowCell(filename, file.getInputStream(), 0);
            //List<DeviceCalibrationDataPo> dataList = deviceCalibrationMapper.getAllDeviceCalibration();

            // 根据对象去重
//            List<DeviceCalibrationDataPo> reduce = list.stream().filter(item -> !dataList.contains(item)).collect(Collectors.toList());
//            System.out.println(" =====之前的=== "+reduce.size());

            // 根据对象的属性去重
//            List<DeviceCalibrationDataPo> differenceSetList = list.stream().filter(a-> !dataList.stream().map(b-> b.getDeviceNo().trim()).collect(Collectors.toList()).contains(a.getDeviceNo().trim())).collect(Collectors.toList());
//            System.out.println("差集 == "+differenceSetList);

            list.stream().forEach(po -> {
                if(StringUtils.isNotEmpty(po.getDeviceNo())){
                    Integer num = deviceCalibrationMapper.getDeviceCalibrationNum(po.getDeviceNo().trim());
                    if(num > 0){
                        System.out.println("删除之前的导入设备 == "+ po.getDeviceNo().trim());
                        deviceCalibrationMapper.deleteDeviceCalibration(po.getDeviceNo().trim());
                    }
                }
            });

            deviceCalibrationMapper.batchInsertByExcel(list);

            String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            filePo.setImportMeteringTime(format);
            deviceRegisterMapper.insertExcelImportInfo(filePo);
        } catch (IOException e) {
            throw new RRException(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}
